package com.itheima.reggie.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component      //将此类交给ioc容器创建
public class LoginCheckInterceptor implements HandlerInterceptor {

    //依赖注入
    @Autowired
    private RedisTemplate redisTemplate;

    //权限拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 取出请求头
        String token = request.getHeader("Authorization");
        //判空
        if (StrUtil.isBlank(token)) {   //空串
            //拦截并返回错误
            errorToReturn(response);
            return false;       //拦截
        }
        //处理Bearer
        token = token.replace(Constant.AUTHORIZATION_HEADER, "");

        //2. jwt解析token
        Map claims = JwtUtil.parseToken(token);
        //判空
        if (claims == null) {   //若空
            //拦截并返回错误
            errorToReturn(response);
            return false;       //拦截
        }
        //3.查询redis取出手机号
        Object phone = claims.get("phone");
        User user = (User) redisTemplate.opsForValue().get(Constant.USER_PHONE_CODE + phone);
        //4. 判断是否有值
        if (user == null) {   //若空
            //拦截并返回错误
            errorToReturn(response);
            //拦截
            return false;
        }

        //5. 授权成功,放行
        //5-1 redis续期
        redisTemplate.opsForValue().set(Constant.USER_PHONE_CODE + phone, user, Duration.ofDays(1));
        //5-2 存入线程中
        UserHolder.set(user);
        return true;    //放行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //从线程中移除
        UserHolder.remove();
    }

    //拦截并返回错误
    private void errorToReturn(HttpServletResponse response) throws Exception {
        ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
        String json = JSON.toJSONString(resultInfo);        //阿里巴巴提供的json转换工具
        response.getWriter().write(json);
    }
}
